package cc.eddic.pratice.programmingparadigms.exam.impl;

import cc.eddic.pratice.programmingparadigms.emp02list.impl.ResultListGcsImpl;
import cc.eddic.pratice.programmingparadigms.exam.ExamService;
import cc.eddic.pratice.programmingparadigms.exam.domain.*;
import com.alibaba.excel.util.StringUtils;
import lombok.Getter;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;

public class ExamServiceLxImpl implements ExamService {
    private static final Logger log = LoggerFactory.getLogger(ResultListGcsImpl.class);

    @Override
    public List<Answer> importAnswers(String answerExcelFile) {
        String fileContent = "试题编号,李惠,谭雨晴,李馨,曾奕哲,车晓满,王巧家,孙晨玮,崔相元,韩睿洁\n" +
                "1,B,B,B,B,B,B,B,B,C\n" +
                "2,C,C,C,C,C,C,C,C,C\n" +
                "3,A,A,A,A,A,B,A,A,A\n" +
                "4,C,C,C,C,C,C,C,B,C\n" +
                "5,D,D,D,D,D,D,D,D,D\n" +
                "6,B,B,B,B,B,D,B,A,B\n" +
                "7,B,B,B,B,B,C,B,C,B\n" +
                "8,A,A,C,A,A,A,A,A,A\n" +
                "9,D,D,D,D,D,D,A,D,D\n" +
                "10,D,B,D,B,D,D,B,D,D\n" +
                "11,B,A,B,C,A,A,A,A,A\n" +
                "12,C,A,C,A,B,C,C,C,C\n" +
                "13,A,A,B,A,A,A,A,A,B\n" +
                "14,A,A,C,C,D,C,A,C,C\n" +
                "15,A,A,A,A,A,B,A,B,A\n" +
                "16,B,B,B,B,B,B,B,B,B\n" +
                "17,A,C,D,D,D,D,D,D,D\n" +
                "18,C,C,C,C,C,C,C,C,C\n" +
                "19,D,D,D,D,D,D,C,A,D\n" +
                "20,B,B,B,B,B,B,B,B,B\n" +
                "21,D,C,C,A,D,D,,A,\n" +
                "22,D,D,D,,D,C,,C,C\n" +
                "23,A,A,A,A,D,D,,C,C\n" +
                "24,C,C,C,C,C,D,A,C,D\n" +
                "25,B,B,B,B,B,B,,D,B";
        String[] answers = fileContent.split("\n");
        List<String> studentName;
        List<Integer> questionNo = new ArrayList<>();
        studentName = Arrays.asList(answers[0].split(",", -1));
        List<List<String>> choice = new ArrayList<>();
        for (int i = 1; i < answers.length; i++) {
            questionNo.add(Integer.parseInt(answers[i].substring(0, answers[i].indexOf(","))));
        }
//        for (int i = 0; i < answers.length; i++) {
//            String[] file = answers[i].split(",", -1);
//            List<String> choiceEvery = new ArrayList<>();
//            for (String s : file) {
//                if (StringUtils.isEmpty(s)) {
//                    choiceEvery.add(" ");
//                } else {
//                    choiceEvery.add(s);
//                }
//            }
//            choice.add(choiceEvery);
//        }
        for (int i = 1; i < answers.length; i++) {
            String[] file = answers[i].split(",", -1);
            List<String> choiceEvery = new ArrayList<>();
            for (String s : file) {
                if (StringUtils.isEmpty(s)) {
                    choiceEvery.add(" ");
                } else if (Character.isLetter(s.charAt(0))) {
                    choiceEvery.add(s);
                }
            }
            choice.add(choiceEvery);
        }
        List<Student> studentList = new ArrayList<>();
        List<Question> questionList = new ArrayList<>();
        List<Answer> answerList = new ArrayList<>();
        MasterDataServiceLxImpl masterDataServiceLx = new MasterDataServiceLxImpl();
        for (int i = 1; i < studentName.size(); i++) {
            String name = studentName.get(i);
            Student student = masterDataServiceLx.find(masterDataServiceLx.getStudents(), s -> s.getName().equals(name))
                    .orElseThrow(() -> new IllegalArgumentException("没找到学生"));
            /*
             *find（）的另一种实现方式
             *
             * Student student = masterDataServiceLx.find(masterDataServiceLx.getStudents(), new Predicate<Student>() {
             *                 @Override
             *                 public boolean test(Student student1) {
             *                     return name.equals(student1.getName());
             *                 }
             *             }).orElseThrow(new Supplier<IllegalArgumentException>() {
             *                 @Override
             *                 public IllegalArgumentException get() {
             *                     return new IllegalArgumentException("");
             *                 }
             *             });
             */
            studentList.add(student);
        }
        QuestionBankServiceLxImpl questionBankServiceLx = new QuestionBankServiceLxImpl();
        for(Integer i:questionNo){
            int no = i;
            Question question = masterDataServiceLx.find(questionBankServiceLx.importCorrectAnswers(""), x -> no == x.getNo()).orElseThrow(() -> new IllegalArgumentException(""));
            questionList.add(question);
        }
        for (int i = 0; i < questionList.size(); i++) {
            for (int j = 0; j < studentList.size(); j++) {
                Answer answer = new Answer(masterDataServiceLx.getExams().get(0), questionList.get(i), studentList.get(j), choice.get(i).get(j).charAt(0));
                answerList.add(answer);
            }

        }
        return answerList;
    }

    //    stream获得学生总分
    public List<StudentScore> score() {
        List<Answer> answerList = importAnswers("");
        return answerList.stream().map(answer -> new AnswerModel(answer.getStudent().getName(), answer.getQuestion().getNo(), answer.getChoice(),
                answer.getQuestion().getOptions().stream().filter(Option::isCorrectAnswer).findFirst()
                        .orElse(new Option("", '*', true)).getChoice()))
//                筛选出学生选择的选项是正确答案的AnswerModel
                .filter(a -> a.getChoice().equals(a.getCorrectAnswer()))
//                按学生姓名分组统计答对的题数
                .collect(Collectors.groupingBy(AnswerModel::getStudengName, Collectors.counting()))
                .entrySet().stream()
//                将信息存放至studentScore并且计算总成绩
                .map(answerMode -> new StudentScore(answerMode.getKey(), answerMode.getValue().intValue() * 4))
//                排序并转成list
                .sorted(Comparator.comparing(StudentScore::getScore).reversed()).collect(Collectors.toList());

    }

    public Map<String, Integer> getScore() {

//        算总分
        List<Answer> answerList = importAnswers("");
        Map<String, Integer> scoreMap = new HashMap<>();
        for (Answer a : answerList) {
            if (log.isDebugEnabled()) log.debug("题号: {},选项:{}", a.getQuestion().getNo(), a.getChoice());
            String name = a.getStudent().getName();
            if (log.isDebugEnabled()) log.debug("姓名: {}", name);
            Option option = a.getQuestion().getOptions().stream().filter(Option::isCorrectAnswer).findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("没找到正确的"));
            if (log.isDebugEnabled()) log.debug("答对的题目: {}", option.getChoice());

            if (option.getChoice() == a.getChoice()) {
                if (scoreMap.containsKey(name)) {
                    scoreMap.put(name, scoreMap.get(name) + 4);
                } else {
                    scoreMap.put(name, 4);
                }
            }
        }
        /*
         *  最原始做法
         *
         * Map<String, Integer> scoreMap = new HashMap<>();
         *         for(Answer a:answerList){
         *             List<Option> optionList=a.getQuestion().getOptions();
         *             for(Option o:optionList){
         *                 if(o.isCorrectAnswer()){
         *                     if(o.getChoice()==a.getChoice()){
         *                         if (scoreMap.containsKey(a.getStudent().getName())) {
         *                             scoreMap.put(a.getStudent().getName(), scoreMap.get(a.getStudent().getName()) + 4);
         *                         } else {
         *                             scoreMap.put(a.getStudent().getName(), 4);
         *                         }
         *                     }
         *
         *                     if (log.isDebugEnabled()) log.debug("学生得分", scoreMap);
         *                 }
         *             }
         *         }
         */

        return scoreMap;
    }

    @Getter
    static class StudentScore {
        StudentScore(String studentName, int score) {
            this.studentName = studentName;
            this.score = score;
        }

        String studentName;
        int score;
    }

    @Getter
    static class AnswerModel {
        String studengName;
        int questionNum;
        Character choice;
        Character correctAnswer;

        public AnswerModel(String studengName, int questionNum, Character choice, Character correctAnswer) {
            this.studengName = studengName;
            this.questionNum = questionNum;
            this.choice = choice;
            this.correctAnswer = correctAnswer;
        }
    }
}
